//
//  WYHttpTask.m
//  QiaQuan_Merchant
//
//  Created by tom on 13-8-3.
//  Copyright (c) 2013年 tom. All rights reserved.
//

#import "WYHttpTask.h"
#import "DBManager.h"
#import "WYDatabase.h"

static NSMutableDictionary *g_mutableDictionary = nil;

@implementation WYHttpTask

@synthesize delegate = _delegate;

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.bRemote = NO;
    }
    return self;
}


-(void)prepare{
    
    //子类重写
    
}


-(id)parese{


    return nil;
}

-(BOOL)bStoreLocalWithKey:(NSString *)key{
    
    NSData *result = [[[DBManager shareInstance:DBTypeCn] db]queryBlobWithKey:key columnIndex:0];
    
    if(!result) return NO;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];
    _rcvData = dic[@"body"];

    DLog(@"%@",_rcvData);
    
    NSLog(@"-------------------华丽数据库分界线--------------------");
    
    return YES;
}


-(void)startAsyncWithParams:(NSDictionary *)params withMethod:(NSString *)method withURL:(NSString *)url{
    
    
//    if(![_db open]){
//        
////判断中英文
//        NSString *path =   [[NSString getFolderWithType:NSCachesDirectory] stringByAppendingPathComponent:@"db_cn.sqlite"];
//        _db = [WYDatabase openDatabaseWitPath:path];
//        /*
//        [db createTableWithSql:@"create table if not exists 'values' ('value' blob, 'key' TEXT);"];
//        [db close];
//        
//        path =   [[NSString getFolderWithType:NSCachesDirectory] stringByAppendingPathComponent:@"db_en.sqlite"];
//        db = [WYDatabase openDatabaseWitPath:path];
//        [db createTableWithSql:@"create table if not exists 'values' ('value' blob, 'key' TEXT);"];
//        [db close];
//         */
//    }
    
    NSString *dbKey = [[NSString stringWithFormat:@"%ld%@%@",(long)[[params description] hash],[method description],[url description]] md5];
    
    MKNetworkEngine *engine = [[MKNetworkEngine alloc] init];
    
    MKNetworkOperation *operation = [engine operationWithURLString:url params:params httpMethod:method];
    
    
    NSString *session = [[NSUserDefaults standardUserDefaults] valueForKey:@"session"];
    if(session.length){
        session = [NSString stringWithFormat:@"PHPSESSID=%@",session];
        [operation addHeaders:@{@"Cookie":session}];
    }
    
    __weak id <WYHttpTaskDelegate> weakDelegate = self.delegate;
    
    __weak WYHttpTask *weakself = self;
    
    NSString *engineKey = [NSString stringWithFormat:@"%ld",(long)[engine hash]];
    
    [operation addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:[completedOperation responseData] options:0 error:nil];
        
        _rcvData = dic[@"body"];
        
        if([_rcvData isEqual:[NSNull null]]) _rcvData = nil;
        
        DLog(@"%@,%@",_rcvData,completedOperation.url);
        
        NSLog(@"-------------------华丽网络分界线--------------------");
        
        if([[dic valueForKey:@"code"] intValue] == 1){
            
            //刷新页面
            if([weakDelegate respondsToSelector:@selector(requestCompleteWithObj:)] && weakDelegate)
                [weakDelegate requestCompleteWithObj:self];
            
            NSString *sql = [NSString stringWithFormat:@"delete from 'values' where 'key' = '%@';",dbKey];
            
            [[[DBManager shareInstance:DBTypeCn] db] deleteWithSql:sql];
            
            [[[DBManager shareInstance:DBTypeCn] db] insertWithValue:[completedOperation responseData] withKey:dbKey];
        }else if([[dic valueForKey:@"code"] intValue] == -1){
            
            DLog(@"重新登录");
        }else if ([[dic valueForKey:@"code"] intValue] == 0){
            
            if([_delegate respondsToSelector:@selector(requestCompleteWithObj:)] && _delegate)
                [_delegate requestCompleteWithObj:self];
        }
        [g_mutableDictionary removeObjectForKey:engineKey];
        
    } errorHandler:^(MKNetworkOperation *errorOp, NSError* error) {
        
         [g_mutableDictionary removeObjectForKey:engineKey];
        
        if([weakself bStoreLocalWithKey:dbKey]){
            
            if([_delegate respondsToSelector:@selector(requestCompleteWithObj:)] && _delegate)
                [_delegate requestCompleteWithObj:self];
            
        }else{
        
            if([weakDelegate respondsToSelector:@selector(requestCompleteWithObj:)] && weakDelegate)
                [weakDelegate requestFailWithMsg:self];
        }
       
    }];
    
    self.networkEngine = engine;
    self.networkOp = operation;
}

-(void)start{

    [self prepare];
    
    if(!g_mutableDictionary){
        
        g_mutableDictionary = [[NSMutableDictionary alloc] initWithCapacity:10];
    }
    
    if(self.networkEngine && self.networkOp){
    
        NSString *engineKey = [NSString stringWithFormat:@"%ud",[self.networkEngine hash]];
        
        [g_mutableDictionary setObject:self.networkEngine forKey:engineKey];
        
        [self.networkEngine enqueueOperation:self.networkOp forceReload:NO];
    }
}

@end
